/**
 * date:2019/06/10
 * author:Mr.Chung
 * description:layuimini 框架扩展
 */

const isCollapsable = function (arg) {
    return arg instanceof Object && Object.keys(arg).length > 0;
};
const isUrl = function (string) {
    const regexp = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
    return regexp.test(string);
};
const json2html = function (json, options) {
    let html = '';
    if (typeof json === 'string') {
        json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
        if (isUrl(json)) html += '<a href="' + json + '" class="json-string">' + json + '</a>';
        else html += '<span class="json-string">"' + json + '"</span>';
    } else if (typeof json === 'number') {
        html += '<span class="json-literal">' + json + '</span>';
    } else if (typeof json === 'boolean') {
        html += '<span class="json-literal">' + json + '</span>';
    } else if (json === null) {
        html += '<span class="json-literal">null</span>';
    } else if (json instanceof Array) {
        if (json.length > 0) {
            html += '[<ol class="json-array">';
            for (let i = 0; i < json.length; ++i) {
                html += '<li>';
                if (isCollapsable(json[i])) {
                    html += '<a href class="json-toggle"></a>';
                }
                html += json2html(json[i], options);
                if (i < json.length - 1) {
                    html += ',';
                }
                html += '</li>';
            }
            html += '</ol>]';
        } else {
            html += '[]';
        }
    } else if (typeof json === 'object') {
        let key_count = Object.keys(json).length;
        if (key_count > 0) {
            html += '{<ul class="json-dict">';
            for (const key in json) {
                if (json.hasOwnProperty(key)) {
                    html += '<li>';
                    const keyRepr = options.withQuotes ? '<span class="json-string">"' + key + '"</span>' : key;
                    if (isCollapsable(json[key])) {
                        html += '<a href class="json-toggle">' + keyRepr + '</a>';
                    } else {
                        html += keyRepr;
                    }
                    html += ': ' + json2html(json[key], options);
                    if (--key_count > 0) html += ',';
                    html += '</li>';
                }
            }
            html += '</ul>}';
        } else {
            html += '{}';
        }
    }
    return html;
};
layui.define(["element", "jquery",'layer','http','vCache'], function (exports) {
    const element = layui.element,
        layer = layui.layer,
        $ = layui.$,
        vCache = layui.vCache,
        http = layui.http;
    let layuimini = new function () {
        this.config = {
          dev:true
        };
        /**
         * 获取对应的id并返回一个数组
         */
        this.ids = function (data, type = 'id') {
            const ids = new Array();
            data.map(function (v) {
                ids.push(v[type]);
            })
            return ids;
        };
        /**
         * 遍历对应的dom，给dom添加默认值 data
         * 要求：input的name必须和data.xxx是一样的
         */
        this.render = function ($dom, data) {
            if (data === undefined || $dom === undefined) {
                return '';
            }
            $.each(data, function (v) {
                $dom.find('[name="' + v + '"][data-each]').val(data[v]);
                const radio_dom = $dom.find('[data-radio] > input[value="' + data[v] + '"]');
                if (radio_dom.length > 0) {
                    radio_dom.attr('checked', true)
                }
            })
        };

        this.render_role_menu_select_dom = function ( data, field = 'name') {
            let dom = '';
            const r = function(v,str = ''){
                return '<option value="'+v.id+'" '+(  v.is_show ?  ( v.is_show !== 'y' ? ' disabled': '') : '')+'>'+str+v[field]+'</option>,';
            };
            data.map(function(v,i){
                dom += r(v);
                if( v.children && v.children.length > 0 ){
                    v.children.map(function ( acv) {
                        dom += r(acv,'|==');
                        if( acv.children && acv.children.length > 0 ){
                            acv.children.map(function (bcv) {
                                dom += r(bcv,'|==|==');
                                if( bcv.children && bcv.children.length > 0){
                                    bcv.children.map( function (ccv) {
                                        dom += r(ccv,'|==|==|==');
                                        if(ccv.childern && ccv.children.length > 0){
                                            ccv.children.map( function (dcv) {
                                                dom += r(dcv,'|==|==|==|==')
                                            })
                                        }
                                    })
                                }
                            })
                        }
                    })
                }
            })
            return dom;
        }


        /**
         *
         * @param dom
         * @returns {{}}
         * 循环某些有相同特征的input并获取它的值
         */
        this.getInputData = function ( dom ) {
            const temp_data = {}
            $(dom).find('input[data-each]').each(function (d,v) {
                temp_data[$(v).attr('name')] = $(v).val()
            })
            return temp_data
        };



        this.format_bytes = (bytes ) => {
            if (bytes === 0 || bytes === '' || bytes === null || bytes === undefined || !bytes) return '0 B';
            const k = 1024;
            let sizes = ['B','KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
            i = Math.floor(Math.log(bytes) / Math.log(k)), num = bytes / Math.pow(k, i);
            return num.toFixed(1) + ' ' + sizes[i];
        };


        /**
         * 生成一个带有时间前缀的随机字符串
         * @returns {string}
         */
        this.randomStr = function( t = ''){
            const d = new Date();
            let y = d.toLocaleDateString();
            if( !t ) t = 'ys-'
            return t+y.split('/').join('-')+'-'+
                (Math.random()*10000000).toString(16).substr(0,4)
                +'-'+(new Date()).getTime()+'-'+Math.random().toString().substr(2,5);
        };

        this.jsonViewer = function(json, options,dom) {
            options = options || {};
            return $(dom).each( function() {
                let html = json2html(json, options);
                if (isCollapsable(json)) html = '<a href class="json-toggle"></a>' + html;
                $(dom).html(html);
                $(dom).off('click');
                $(dom).on('click', 'a.json-toggle',
                    function () {
                        const target = $(this).toggleClass('collapsed').siblings('ul.json-dict, ol.json-array');
                        target.toggle();
                        if (target.is(':visible')) {
                            target.siblings('.json-placeholder').remove();
                        } else {
                            const count = target.children('li').length;
                            const placeholder = count + (count > 1 ? ' items' : ' item');
                            target.after('<a href class="json-placeholder">' + placeholder + '</a>');
                        }
                        return false;
                    });
                $(dom).on('click', 'a.json-placeholder',
                    function () {
                        $(this).siblings('a.json-toggle').click();
                        return false;
                    });
                if (options.collapsed == true) {
                    $(dom).find('a.json-toggle').click();
                }
            })


        }
        /**
         * 初始化设备端
         */
        this.initDevice = function () {
            if (layuimini.checkMobile()) {
                $('.layuimini-tool i').click();
                $('.layuimini-tool i').attr('class', 'layui-icon layui-icon-shrink-right');
                $('.layui-layout-body').attr('class', 'layui-layout-body layuimini-mini');
            }
        };
        /**
         * 初始化页面标题，并自动展开菜单栏
         * @param href 链接地址
         * @param title 页面标题
         */
        this.initPageTitle = function (href, title) {
            window.pageHeader = (title == undefined || title == '' || title == null) ? [] : [title];
            $("[data-one-page]").each(function () {
                if ($(this).attr("data-one-page") == href) {
                    const addMenuClass = function ($element, type) {
                        let moduleTile;
                        let moduleId;
                        if (type == 1) {
                            $element.addClass('layui-this');
                            if (title == undefined || title == '' || title == null) {
                                let thisPageTitle = $element.text();
                                thisPageTitle = thisPageTitle.replace(/\s+/g, "");
                                pageHeader.push(thisPageTitle);
                            }
                            if ($element.attr('class') != 'layui-nav-item layui-this') {
                                addMenuClass($element.parent().parent(), 2);
                            } else {
                                moduleId = $element.parent().attr('id');
                                moduleTile = $("#" + moduleId + "HeaderId").text();
                                moduleTile = moduleTile.replace(/\s+/g, "");
                                pageHeader.push(moduleTile);
                                $(".layui-header-menu li").attr('class', 'layui-nav-item');
                                $("#" + moduleId + "HeaderId").addClass("layui-this");
                                $(".layui-left-nav-tree").attr('class', 'layui-nav layui-nav-tree layui-hide');
                                $("#" + moduleId).attr('class', 'layui-nav layui-nav-tree layui-this');
                            }
                        } else {
                            $element.addClass('layui-nav-itemed');
                            let parentTitle = $element.text();
                            parentTitle = parentTitle.replace(/^\s+|\s+$/g, "").split('\n');
                            pageHeader.push(parentTitle[0]);
                            if ($element.attr('class') != 'layui-nav-item layui-nav-itemed') {
                                addMenuClass($element.parent().parent(), 2);
                            } else {
                                moduleId = $element.parent().attr('id');
                                moduleTile = $("#" + moduleId + "HeaderId").text();
                                moduleTile = moduleTile.replace(/\s+/g, "");
                                pageHeader.push(moduleTile);
                                $(".layui-header-menu li").attr('class', 'layui-nav-item');
                                $("#" + moduleId + "HeaderId").addClass("layui-this");
                                $(".layui-left-nav-tree").attr('class', 'layui-nav layui-nav-tree layui-hide');
                                $("#" + moduleId).attr('class', 'layui-nav layui-nav-tree layui-this');
                            }
                        }
                    };
                    addMenuClass($(this).parent(), 1);
                    let pageHeaderHtml = '<a href="javascript:;" data-load-page="page/index_croe.html">主页</a><span lay-separator="">/</span>\n';
                    for (let i = pageHeader.length - 1; i >= 0; i--) {
                        pageHeader[i] = pageHeader[i].replace(/\s+/g, "");
                        if (i != 0) {
                            pageHeaderHtml += '<a><cite>' + pageHeader[i] + '</cite></a><span lay-separator="">/</span>\n';
                        } else {
                            pageHeaderHtml += '<a><cite>' + pageHeader[i] + '</cite></a>\n';
                        }
                    }
                    $('.layuimini-page-header').removeClass('layui-hide');
                    $('#layuimini-page-header').empty().html(pageHeaderHtml);
                    return false;
                }
            });
        };
        /**
         * 初始化内容信息 增加cache随机码
         * @param container
         * @param href
         * @param isHash
         */
        this.initConten = function (href = '') {
            let url = href;
            if (href) {
                const container = '.layuimini-content-page'
                if(this.config.dev === true){
                    let v = new Date().getTime(),
                    url = href.indexOf("?") > -1 ? href + '&v=' + v : href + '?v=' + v;
                }
                $(container).load(url, function (res, err, xhr) {
                    if (xhr.status !== 200) {
                        if (xhr.status === 404) {
                            $(container).load('page/404.html')
                        } else {
                            layer.msg('发生错误！没有可以加载的页面')
                        }

                    } else {
                        layuimini.initPageTitle(href);
                    }
                })
            }
        };

        /**
         * 初始化菜单栏
         * @param data
         */
        this.initMenu = function (data) {
            let headerMenuHtml = '',
                headerMobileMenuHtml = '',
                leftMenuHtml = '',
                headerMenuCheckDefault = 'layui-this',
                leftMenuCheckDefault = 'layui-this';
            window.menuParameId = 1;
            const childHtml = function( {id,href,icon,title} ){
               return '<a href="javascript:;" class="layui-menu-tips"'+
                    ' data-type="tabAdd" data-menu-id="'+id+
                   '" data-one-page-mpi="m-p-i-' + menuParameId +
                   '" data-one-page="' + href + '"><i class="layui-icon ' +
                    icon + '"></i><span class="layui-left-nav" data-nav-name="'+
                   title +'"> ' + title + '</span></a>\n';
            };
            $.each(data, function (key, val) {
                headerMenuHtml += '<li class="layui-nav-item ' + headerMenuCheckDefault + '" id="' + key + 'HeaderId" data-menu="' + val.id + '"> <a href="javascript:;"><i class="layui-icon ' + val.icon + '"></i> ' + val.title + '</a> </li>\n';
                headerMobileMenuHtml += '<dd><a href="javascript:;" id="' + key + 'HeaderId" data-menu="' + val.id + '"  ><i class="layui-icon ' + val.icon + '"></i> ' + val.title + '</a></dd>\n';
                leftMenuHtml += '<ul class="layui-nav layui-nav-tree layui-left-nav-tree ' + leftMenuCheckDefault + '" id="' + key + '" lay-shrink="all">\n';
                const menuList = val.child;
                $.each(menuList, function (index, menu) {
                    leftMenuHtml += '<li class="layui-nav-item">\n';
                    if (menu.child !== undefined && menu.child != []) {
                        leftMenuHtml += '<a href="javascript:;" class="layui-menu-tips" ><i class="layui-icon ' + menu.icon + '"></i><span class="layui-left-nav" data-nav-name="'+ menu.title +'"> ' + menu.title + '</span> </a>';
                        const buildChildHtml = function (html, child, menuParameId) {
                            html += '<dl class="layui-nav-child">\n';
                            $.each(child, function (childIndex, childMenu) {
                                html += '<dd>\n';
                                if (childMenu.child != undefined && childMenu.child != []) {
                                    html += '<a href="javascript:;" class="layui-menu-tips" ><i class="layui-icon ' + childMenu.icon + '"></i><span class="layui-left-nav" data-nav-name="'+ childMenu.title +'"> ' + childMenu.title + '</span></a>';
                                    html = buildChildHtml(html, childMenu.child, menuParameId);
                                } else {
                                    html += childHtml(childMenu);
                                    menuParameId++;
                                    window.menuParameId = menuParameId;
                                }
                                html += '</dd>\n';
                            });
                            html += '</dl>\n';
                            return html;
                        };
                        leftMenuHtml = buildChildHtml(leftMenuHtml, menu.child, menuParameId);
                    } else {
                        leftMenuHtml += childHtml(menu)
                        menuParameId++;
                    }
                    leftMenuHtml += '</li>\n';
                });
                leftMenuHtml += '</ul>\n';
                headerMenuCheckDefault = '';
                leftMenuCheckDefault = 'layui-hide';
            });
            $('.layui-header-pc-menu').html(headerMenuHtml); //电脑
          //  $('.layui-header-mini-menu').html(headerMobileMenuHtml); //手机
            $('.layui-left-menu').html(leftMenuHtml);
            element.init();
        };

        this.initMenuDot = function ( is_has_notice = 0, t = true) {
            if(is_has_notice){
                const target_dom = $('[data-menu-id="'+is_has_notice+'"]');
                if( target_dom.find('.layui-badge-dot').length <= 0 && t){
                    target_dom.append('<span class="layui-badge-dot"></span>')
                } else if( target_dom.find('.layui-badge-dot').length > 0 && t===false ){
                    target_dom.find('.layui-badge-dot').remove()
                }
                const finds = function ( target_dom,t ) {
                     if(target_dom.length > 0){
                         const p1 = target_dom.parents('.layui-nav-child');
                         if(p1.length > 0){
                             const tips1 = p1.siblings('.layui-menu-tips');
                             if(tips1.length > 0){
                                 if(tips1.find('.layui-badge-dot').length <= 0 && t){
                                     tips1.append('<span class="layui-badge-dot"></span>')
                                 } else if(tips1.find('.layui-badge-dot').length > 0 && t===false) {
                                     tips1.find('.layui-badge-dot').remove()
                                 }
                             }
                             if(tips1.length > 0){
                                 if(tips1.parents('.layui-nav-child').length > 0){
                                     finds(tips1,t)
                                 }
                             }
                         }
                     }
                };
                finds(target_dom,t);

            }
        }
        /**
         * 判断是否为手机
         */
        this.checkMobile = function () {
            const ua = navigator.userAgent.toLocaleLowerCase();
            const pf = navigator.platform.toLocaleLowerCase();
            const isAndroid = (/android/i).test(ua) || ((/iPhone|iPod|iPad/i).test(ua) && (/linux/i).test(pf))
                || (/ucweb.*linux/i.test(ua));
            const isIOS = (/iPhone|iPod|iPad/i).test(ua) && !isAndroid;
            const isWinPhone = (/Windows Phone|ZuneWP7/i).test(ua);
            const clientWidth = document.documentElement.clientWidth;
            if (!isAndroid && !isIOS && !isWinPhone && clientWidth > 768) {
                return false;
            } else {
                return true;
            }
        };
        this.side_fold = function (i = 0, $dom) {
            const logo_dom = $('.layui-header .layui-logo > a');
            const title = logo_dom.find('h1').text();
            const hide_text = function( i )            {
                $.each( $('.layui-left-menu li a .layui-left-nav '),function (v,dom) {
                    if( +i == 1) {
                        $(dom).text('');
                    }else {
                        $(dom).text(' ' + $(dom).attr('data-nav-name'))
                    }
                })
            }
            if (i === 1) { // 缩放
                logo_dom.append(title.substr(0, 1)).css({'font-size':'25px','color':'#fff'});
                $dom.attr('data-side-fold', 0);
                $('.layuimini-tool i').addClass('layui-icon-spread-left');
                $('.layui-layout-body').attr('class', 'layui-layout-body layuimini-mini');
            } else { // 正常
                logo_dom.html('<h1>' + title + '</h1>')
                $dom.attr('data-side-fold', 1);
                $('.layuimini-tool i').removeClass('layui-icon-spread-left').addClass('layui-icon-shrink-right');
                $('.layui-layout-body').attr('class', 'layui-layout-body layuimini-all');
            }
            hide_text(i)
        }
        this.changePageCallback = null;
    };

        /**
         * 打开新窗口
         */
        $('body').on('click', '[data-one-page]', function () {
            const href = $(this).attr('data-one-page'),
                title = $(this).text();
            if( href && href != '0'){
                typeof layuimini.changePageCallback === 'function' && layuimini.changePageCallback();
                layuimini.initPageTitle(href, title);
                layuimini.initConten(href);
                layuimini.initDevice();
                vCache.sSet('load_url',href)
            }else{
                layer.msg('发生错误，没有可以加载的页面')
            }
        });
    /**
     * 左侧菜单的切换
     */
    $('body').on('click', '[data-menu]', function () {
        let menuId = $(this).attr('data-menu');
        // header
        $(".layui-header-menu .layui-nav-item.layui-this").removeClass('layui-this');
        $(this).addClass('layui-this');
        // left
        $(".layui-left-menu .layui-nav.layui-nav-tree.layui-this").addClass('layui-hide');
        $(".layui-left-menu .layui-nav.layui-nav-tree.layui-this.layui-hide").removeClass('layui-this');
        $("#" + menuId).removeClass('layui-hide');
        $("#" + menuId).addClass('layui-this');
    });

    /**
     * 菜单栏缩放
     */
    $('body').on('click', '[data-side-fold]', function () {
        const isShow = $(this).attr('data-side-fold');
        vCache.sSet('side_fold_is_show', +isShow )
        layuimini.side_fold( +isShow ,$(this));
    });

    /**
     * 监听提示信息
     */
    $("body").on("mouseenter", ".layui-menu-tips", function () {
        const tips = $(this).children('span').attr('data-nav-name'),
            isShow = $('.layuimini-tool i').attr('data-side-fold');
         window.openTips = null;
        if (isShow == 0) {
          window.openTips = layer.tips(tips, $(this), {tips: [2, '#2f4056'], time: 30000});
        }
    });
    $("body").on("mouseleave", ".layui-menu-tips", function () {
        const isShow = $('.layuimini-tool i').attr('data-side-fold');
        if (isShow == 0) {
            try {
                layer.close(window.openTips);
            } catch (e) {
                console.log(e.message);
            }
        }
    });
    exports("layuimini", layuimini);
});
